﻿using Microsoft.AspNetCore.SignalR;

namespace ARPaintServer.Hubs
{
	public class ChatHub:Hub
	{
		
		private Dictionary<string, string> _connectionIdToUserName=new();
		private Dictionary<string, string> _UserNameToGroupName = new();

		public async Task SendMessage(string user, string message)
		{			
			await Clients.All.SendAsync("ReceiveMessage",user, message);
		}

		public Task SendPrivateMessage(string user, string message)
		{
			return Clients.User(user).SendAsync("ReceiveMessage", message);
		}

		public async Task AddToGroup(string groupName,string userName)
		{
			await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

			await Clients.Group(groupName).SendAsync("NewPlayerEnterGroup", Context.ConnectionId,userName);

			_connectionIdToUserName[Context.ConnectionId]= userName;
			_UserNameToGroupName.Add(userName, groupName);

			Console.WriteLine($"<{Context.ConnectionId}>(<{userName}>) 加入了 <{groupName}>");
		}

		public async Task RemoveFromGroup(string groupName)
		{
			await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);

			await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has left the group {groupName}.");
		}


		public async Task<string> GetConnectionId()
		{
			return await Task.FromResult(Context.ConnectionId);
		}

		public async Task<List<string>> GetGroupPlayerNames(string groupName)
		{
			var nameList = new List<string>();

			var list=_UserNameToGroupName.GroupBy(kvp=>kvp.Value).ToList();			
			foreach (var item in list)
			{
				foreach (var subitem in item)
				{
					if(subitem.Value == groupName)
					{
						nameList.Add(subitem.Key);
					}				
				}
			}

			return await Task.FromResult(nameList);
		}


		public async Task<int> ReturnNumber(int input)
		{
			int i = input;
			i += 1;
			Console.WriteLine("给他们点数字!");
			await Task.Delay(1000);
			return i;
		}

		
		public override Task OnConnectedAsync()
		{
			Console.WriteLine($"加入了一个新用户{Context.ConnectionId}");

			_connectionIdToUserName.Add(Context.ConnectionId, "UnKnow");
			//Clients.All.SendAsync();
			return Task.CompletedTask;
		}

		public override Task OnDisconnectedAsync(Exception? exception)
		{		
			//_UserNameToGroupName.Remove(_connectionIdToUserName[Context.ConnectionId]);
			//_connectionIdToUserName.Remove(Context.ConnectionId);
			Console.WriteLine($"{Context.ConnectionId}离开了!");
			return base.OnDisconnectedAsync(exception);
		}
	}
}
